<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .wrapAll {
      padding: 10px;
    }

    .buttons button+button {
      margin-left: 10px;
    }

    .wrap {
      width: 1100px;
      height: 100px;
      border: 1px solid #333;
      margin-top: 10px;
      position: relative;
    }

    .sub {
      width: 100px;
      height: 100px;
      background-color: #6ff;
      position: absolute;
      left: 00px;
    }
  </style>
</head>

<body>
  <div class="wrapAll">
    <div class="buttons">
      <button class="start">开始</button>
      <button class="pause">暂停</button>
      <button class="back">返回</button>
    </div>
    <div class="wrap">
      <div class="sub"></div>
    </div>
  </div>
</body>
<script>
  // JS运动
  // 每隔一段时间,移动盒子的位置

  // 每隔一段时间  => 计时器
  // 移动盒子      =>  margin  position:left  translate:translateX()

  // => 通过计时器 每隔固定的时间 改变元素的位置

  var start = document.getElementsByClassName("start")[0];
  var pause = document.getElementsByClassName("pause")[0];
  var back = document.getElementsByClassName("back")[0];
  var sub = document.getElementsByClassName("sub")[0];

  var timer = null;

  // 正向运动 (0-1000)
  start.onclick = function () {
    animate(sub, "1000px")
  }

  pause.onclick = function () {
    clearInterval(timer);
  }

  // 反向运动 (1000 - 0)
  back.onclick = function () {
    animate(sub, 100)
  }

  function animate(ele, end) {
    var cur = ele.offsetLeft;  //  cur 1. 记录盒子最开始的初始值  2. 记录每次运动时的当前位置
    end = parseFloat(end);
    var speed = end > cur ? 10 : -10;
    clearInterval(timer);
    timer = setInterval(function () {
      cur += speed;
      ele.style.left = cur + "px";
      if (Math.abs(end - cur) < Math.abs(speed)) {  // cur >= 100   超出临界值
        clearInterval(timer);
        ele.style.left = end + "px";   //强制到达终点
      }
    }, 10);
  }




</script>

</html>